/*
 *   The contents of this file are subject to the Mozilla Public License
 *   Version 1.1 (the "License"); you may not use this file except in
 *   compliance with the License. You may obtain a copy of the License at
 *   http://www.mozilla.org/MPL/
 *
 *   Software distributed under the License is distributed on an "AS IS"
 *   basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 *   License for the specific language governing rights and limitations
 *   under the License.
 *
 *   The Original Code is Matra - the DTD Parser.
 *
 *   The Initial Developer of the Original Code is Conrad S Roche.
 *   Portions created by Conrad S Roche are Copyright (C) Conrad 
 *   S Roche. All Rights Reserved.
 *
 *   Alternatively, the contents of this file may be used under the terms
 *   of the GNU GENERAL PUBLIC LICENSE Version 2 or any later version
 *   (the  "[GPL] License"), in which case the
 *   provisions of GPL License are applicable instead of those
 *   above.  If you wish to allow use of your version of this file only
 *   under the terms of the GPL License and not to allow others to use
 *   your version of this file under the MPL, indicate your decision by
 *   deleting  the provisions above and replace  them with the notice and
 *   other provisions required by the GPL License.  If you do not delete
 *   the provisions above, a recipient may use your version of this file
 *   under either the MPL or the GPL License."
 *
 *   [NOTE: The text of this Exhibit A may differ slightly from the text of
 *   the notices in the Source Code files of the Original Code. You should
 *   use the text of this Exhibit A rather than the text found in the
 *   Original Code Source Code for Your Modifications.]
 *
 * Created: Conrad S Roche <derupe at users.sourceforge.net>,  29-Jul-2003
 */
package com.conradroche.matra.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
//import java.util.Properties;

import com.conradroche.matra.data.DTDData;
import com.conradroche.matra.exception.DTDException;

/**
 * Class to do the io operations for a URL.
 * 
 * @author Conrad Roche
 */
public class DTDUrl extends DTDSource {

	/**
	 * The URL which is the source of the data.
	 */
	private URL url;
	
	/**
	 * DTDUrl Constructor.
	 * 
	 * @param url The location of the dtd.
	 */
	public DTDUrl(String url) {
		super(url);
		try {
			this.url = new URL(url);
		} catch(MalformedURLException me) {
			//CR: TODO: Handle this!
		}
	}

	/**
	 * DTDUrl Constructor.
	 * 
	 * @param base The base URL.
	 * @param relative The relative URL.
	 */
	public DTDUrl(String base, String relative) {
		super(base, relative);
	}

	/**
	 * Return the absolute path of the source
	 * using the path relative to this source.
	 *
	 * @return The abosolute path of the source.
	 * @param relative The relative path of the source w.r.t. 
	 * 			the current location of this source.
	 */
	public DTDSource getAbsolute(String relative) {
		
		/*
		 * If this is a proper url - use it as it is
		 * If this is the absolute path for the doc w.r.t the host - append it to the host
		 * If this is a relative path - specify it w.r.t to the url doc path.
		 */
		 
		 //absolute file location on the same host
		 if(relative.charAt(0) == '/') {
		 	String newUrl = url.getProtocol() + url.getHost();
		 	if(url.getPort() != 80) {
		 		newUrl += ":" + url.getPort();
		 	}
		 	newUrl += relative;
		 	
		 	return new DTDUrl(newUrl);
		 } else {
		 	
			String newUrl = location.substring(0, location.lastIndexOf("/") + 1);
			
			newUrl += relative;
		 	
			return new DTDUrl(newUrl);
		 }
		 
		//CR: TODO: Handle the remaining cases
	}

	/**
	 * Returns the name of the DTD File.
	 * 
	 * @return The name of the DTD File.
	 */
	public String getDTDFilename() {
		return url.getFile();
	}

	/**
	 * Method to perform the read operation on this url source.
	 * 
	 * @return The DTDData object containing all the read data
	 * 			from the current source.
	 * 
	 * @throws DTDException If the url resource could not be read.
	 */
	public DTDData read() throws DTDException {

//		Properties prop = System.getProperties(); 
//		prop.put("proxySet", "true" ); 
//		prop.put("http.proxyHost","localhost"); 
//		prop.put("http.proxyPort","8888"); 

		try {
			URLConnection connection = url.openConnection(); 
	                
	//		String userPassword = "username" + ":" + "password"; 
	//		String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes()); 
	//		yc.setRequestProperty ("Authorization", "Basic " + encoding); 
	                
			BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream())); 
			String inputLine;
			StringBuffer dtdStr = new StringBuffer(""); 
	
			while ((inputLine = in.readLine()) != null) { 
				dtdStr.append(inputLine); 
			}
			in.close(); 
			
			return new DTDData(dtdStr.toString());
			
		} catch(IOException ie) {
//			ie.printStackTrace();
			//CR: TODO: nest this exception
			throw new DTDException("Error reading url - " + url.toString());
		}
	}
}
